<template>
    <vc-primitive :appearance="primitiveAppearance" :geometryInstances="geometryInstances" v-if="visible" />
</template>

<script setup>
import { ref, toRefs, watch } from 'vue'
import { VcPrimitive } from 'vue-cesium'
import { ElMessage } from 'element-plus'
import api from '@/api'

const props = defineProps({
    visible: Boolean
})

const { visible } = toRefs(props)

const noFlyGrids = ref([])
const geometryInstances = ref([])
const primitiveAppearance = ref(null)

watch(visible, (newValue, oldValue) => {
    if (newValue) {
        getNoFlyGrid()
    } else {
        noFlyGrids.value = []
        geometryInstances.value = []
    }
})

const getNoFlyGrid = async () => {
    const result = await api.getNoFlyGrid()
    if (result.code === 200) {
        noFlyGrids.value = result.data || []
        updateGeometryInstances()
    } else {
        ElMessage.error(result.msg || '服务器忙，请稍后重试！')
    }
}

const updateGeometryInstances = () => {
    geometryInstances.value = noFlyGrids.value.map(grid => {
        const dimensions = new Cesium.Cartesian3(grid.edgeLength / 2, grid.edgeLength / 2, grid.edgeLength / 2)
        const position = Cesium.Cartesian3.fromDegrees(grid.longitude, grid.latitude, grid.height)
        const modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(position);
        return new Cesium.GeometryInstance({
            geometry: new Cesium.BoxGeometry({
                vertexFormat: Cesium.VertexFormat.POSITION_AND_NORMAL,
                maximum: dimensions,
                minimum: new Cesium.Cartesian3(-grid.edgeLength / 2, -grid.edgeLength / 2, -grid.edgeLength / 2)
            }),
            modelMatrix: modelMatrix,
            attributes: {
                color: Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.fromCssColorString(grid.areoTypeColor))
            }
        })
    })

    primitiveAppearance.value = new Cesium.PerInstanceColorAppearance({
        flat: true,
        translucent: true
    })
}
</script>

<style scoped></style>